﻿using System;
using System.Net;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace TcpSocketTaskDemo
{
    static class Utility
    {
        public static void ContiExcepToDispose<TResult>(this Task<TResult> task, IDisposable disposable)
        {
            task.ContinueWith(ante =>
                                  {
                                      Console.WriteLine("!!! Exception: {0}", ante.Exception);
                                      disposable.Dispose();
                                  }, TaskContinuationOptions.OnlyOnFaulted);
        }

        public static IPEndPoint CreateEndPoint(string hostNameOrAddress, int port)
        {
            if (string.IsNullOrEmpty(hostNameOrAddress))
            {
                return new IPEndPoint(IPAddress.Any, port);
            }
            else
            {
                IPAddress address;
                if (IPAddress.TryParse(hostNameOrAddress, out address))
                    // Use the provided IP address.
                    return new IPEndPoint(address, port);
                else
                    // Exception will occur if DNS lookup fails.
                    return new IPEndPoint(Dns.GetHostEntry(hostNameOrAddress).AddressList[0], port);
            }
        }

        public static IEnumerable<string> IntervalStrFactory(int interval, int total)
        {
            for (int index = 0; index < total; index++)
            {
                yield return string.Format("hello-{0}", index);
                Thread.Sleep(interval);
            }// for
        }

        public static void WaitUserSignal()
        {
            Console.WriteLine("Enter any key to continue,......");
            Console.ReadLine();
        }
    }// class Utility
}
